<template>
    <el-dialog v-model="fromParam.modal" title="修改密码" width="580" @close="PasswordCloseReset">
        <el-form ref="passwordForm" :model="params" label-width="120" :rules="rules">
            <el-form-item label="新密码:" prop="Password">
                <el-input type="password" v-model="params.Password" placeholder="6-18位英文字母，数字，或数字字母组合" clearable
                    show-password />
            </el-form-item>
            <el-form-item label="确认密码:" prop="CofPassword">
                <el-input type="password" v-model="params.CofPassword" placeholder="请输入和上面相同的密码" clearable show-password />
            </el-form-item>
        </el-form>
        <div slot="footer" class="modal-footer">
            <el-button @click="PasswordCloseReset">取消</el-button>
            <el-button type="primary" @click="UpdatePassowrd">提交</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, ref, watch } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { PermessionUser } from './Def';
import { UserApi } from '@/api/permession/user';
import MessageUti from "@/library/utils/MessageUti"

const props = defineProps<{
    fromParam: PermessionUser.ChangePasswordDialog,
    GetData: () => void
}>()

const passwordParams = ref<PermessionUser.PasswordFormState>({
    Id: -1,
    Password: '',
    CofPassword: ''
})

const params = ref<PermessionUser.PasswordFormState>({ ...passwordParams.value })

watch(() => props.fromParam.row, (val) => {
    params.value.Id = val.Id!
})

const ConfirmPasswordCheck = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('密码不能为空'))
    } else if (value !== params.value.Password) {
        callback(new Error('输入的密码与确认密码不匹配'))
    } else {
        callback()
    }
}

const rules = ref<FormRules<PermessionUser.PasswordFormState>>({
    Password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    CofPassword: [{ required: true, validator: ConfirmPasswordCheck, trigger: 'blur' }]
})

const passwordForm = ref<FormInstance>()
const UpdatePassowrd = async () => {
    if (!passwordForm.value) return
    await passwordForm.value.validate((valid) => {
        if (valid) {
            let param = {
                ...params.value,
                CofPassword: undefined
            }

            UserApi.UpdateUserPassword({ ...param }).then((res) => {
                MessageUti.showSuccess('修改成功')
                PasswordCloseReset()
                props.GetData()
            })
        }
    })
}

const PasswordCloseReset = () => {
    if (!passwordForm.value) return
    props.fromParam.modal = false
    nextTick(() => {
        params.value = { ...passwordParams.value }
        passwordForm.value?.resetFields()
    })
}

</script>

<style scoped></style>